<template>
    <div class="view">
        <nav-bar title="交友" :fixed="false" leftText="情感咨询" color="#ec6786" @clickLeft="toExpertList" rightText="搜索" @clickRight="selectDrwaerHandle"></nav-bar>
        <div class="friend-head" @click="toPage('loveArticle')">
            <!--            <img :src="`${publicPath}/img/base/love-article.jpg`" class="friend-head-image">-->
            <img :src="loveArticleImg?loveArticleImg+'?imageView2/0/w/'+clientWidth+'/q/90':`${publicPath}img/base/love-article.jpg`">
            <!--            <div class="handle">点击进入情感空间</div>-->
        </div>
        <div class="friend-filter-nav">
            <span>搜索条件：</span>
            <span class="tag" v-for="(tag,index) in tagList" :key="index">{{tag}}</span>
        </div>
        <div class="none-friends" v-if="!friends.length">暂无好友!</div>
        <cube-scroll class="scroll" v-else ref="scroll" :data="friends" :options="options" @pulling-down="onPullingDown" @pulling-up="onPullingUp">
            <ul class="list-wrapper">
                <li v-for="(item, index) in friends" class="list-item flex" :key="index" @click="toPage('friendInfo',{friendId:item.user_id})">
                    <div class="avatar">
                        <img :src="item.avatar&&item.avatar.file_status.status?(item.avatar.file_path+'?imageView2/0/w/70'):filePath">
                    </div>
                    <div class="info">
                        <div class="nickname ellipsis">{{item.nickName}}
                            <svg class="svg-icon huangguan" aria-hidden="true">
                                <use :xlink:href="item.gender==1?'#icon-chinese':item.gender==2?'#icon-xinniang':'#icon-nicheng'"></use>
                            </svg>
                        </div>
                        <div class="rank">
                            {{item.rank_name}}
                            <svg class="svg-icon huangguan" aria-hidden="true">
                                <use :xlink:href="item.user_rank==1?'#icon-putong':item.user_rank==2?'#icon-VIPhuangguan':'#icon-huiyuan'"></use>
                            </svg>
                        </div>
                        <div class="factor ellipsis">
                            <span class="age" v-if="!(item.age=='未知'||item.age==0)">{{item.age+'岁'}}</span>
                            <!--                                                    <span class="height" v-if="item.user.user_info.SNAP_HEIGHT!=='未填写'">{{item.user.user_info.SNAP_HEIGHT}}</span>-->
                            <span class="home" v-if="!(item.snap_city_id=='未填写'||item.snap_city_id=='')">{{item.snap_city_id}}</span>
                        </div>
                        <div class="hobby ellipsis" v-if="item.user_info.SNAP_HOBBY!=='未填写'">
                            {{item.user_info.SNAP_HOBBY}}
                        </div>
                        <div class="handdle">
                            <span class="distance lf">
                                <svg class="svg-icon huangguan" aria-hidden="true">
                                    <use xlink:href="#icon-position"></use>
                                </svg>&nbsp;{{item.distance===-1?'暂无定位':(item.distance | distanceFilter)}}
                            </span>
                            <span class="like" @click.stop="like(item.like,item.user_id,index)"><i class="iconfont" :class="item.like?'icon-icon-aixin- animated bounceIn':'icon-icon-aixin-1'"
                                                                                                   style="display: inline-block;">&nbsp;</i>喜欢</span>
                            <span class="chat" @click.stop="toPage('chatDetail',{toId:item.user_id})"><i class="iconfont icon-iconfontquanbuxiaoxizhengchang">&nbsp;</i>聊天</span>
                        </div>
                    </div>
                </li>
            </ul>
        </cube-scroll>
        <div :class="'select-drawer '+ (selectDrawerShow?'':'hide')">
            <div class="select-drawer-mask" @click="selectDrwaerHandle"></div>
            <div class="select-drawer-content">
                <div class="select-drawer-content-title">请选择</div>
                <div class="content-box">
                    <div class="car flex" @click="showDiffPicker('年龄区间','mate_age','mate_age_snap','AGE','','mateSelection')">
                        <span>年龄</span>
                        <span class="ellipsis">
                            {{selectValue.mate_age_snap}}
                            <i class="iconfont icon-youbian"></i>
                        </span>
                    </div>
                    <div class="car flex"
                         @click="showDiffPicker('身高区间','mate_height','mate_height_snap','HEIGHT_OPTIONS','','mateSelection')">
                        <span>身高</span>
                        <span class="ellipsis">
                             {{selectValue.mate_height_snap}}
                            <i class="iconfont icon-youbian"></i></span>
                    </div>
                    <div class="car flex"
                         @click="showDiffPicker('学历区间','mate_education','mate_education_snap','EDUCATION_OPTIONS','','mateSelection')">
                        <span>学历</span>
                        <span class="ellipsis">
                             {{selectValue.mate_education_snap}}
                            <i class="iconfont icon-youbian"></i></span>
                    </div>
                    <div class="car flex"
                         @click="showDiffPicker('月收入区间','mate_income','mate_income_snap','INCOME_OPTIONS','','mateSelection')">
                        <span>月收入</span>
                        <span class="ellipsis">
                            {{selectValue.mate_income_snap}}
                            <i class="iconfont icon-youbian"></i>
                        </span>
                    </div>
                    <div class="car flex"
                         @click="showAddressPicker('选择居住地',['mate_province','mate_city'],['mate_province_snap','mate_city_snap'],'mateSelection')">
                        <span>居住地</span>
                        <span class="ellipsis">
                            {{[selectValue.mate_province_snap,selectValue.mate_city_snap].join(',')}}
                            <i class="iconfont icon-youbian"></i></span>
                    </div>
                    <div class="car flex"
                         @click="showCommonPicker('婚姻情况','mate_marital','mate_marital_snap','MARITAL_STATUS_OPTIONS','','mateSelection')">
                        <span>婚姻情况</span>
                        <span class="ellipsis">
                            {{selectValue.mate_marital_snap}}
                            <i class="iconfont icon-youbian"></i></span>
                    </div>
                    <div class="car flex"
                         @click="showCommonPicker('购房情况','mate_housing','mate_housing_snap','HOUSE_PURCHASE_OPTIONS','','mateSelection')">
                        <span>购房情况</span>
                        <span class="ellipsis">
                              {{selectValue.mate_housing_snap}}
                            <i class="iconfont icon-youbian"></i>
                        </span>
                    </div>
                    <div class="car flex"
                         @click="showCommonPicker('子女情况','mate_child','mate_child_snap','CHILD_OPTIONS','','mateSelection')">
                        <span>子女情况</span>
                        <span class="ellipsis">
                              {{selectValue.mate_child_snap}}
                            <i class="iconfont icon-youbian"></i>
                        </span>
                    </div>
                </div>
                <div class="select-drawer-btn" @click="selectSubmit">确定</div>
                <div class="select-drawer-btn  select-drawer-btn-cancel" @click="selectReset">重置</div>


            </div>
        </div>
    </div>
</template>

<script lang="ts">
    import {Component, Vue} from "vue-property-decorator";
    import Scene from "@/render/Scene";
    import Http from "@/service/Http";
    import DialogConfig from "@/constant/DialogConfig";
    import {Getter, Action, State, Mutation} from "vuex-class";
    import {InterfaceUser} from "@/interface/InterfaceUser";
    import NavBar from "@/components/aui/NavBar.vue";

    import CommonUnit from "@/unit/CommonUnit";

    @Component({
        components: {
            NavBar
        }
    })
    export default class Friend extends Scene {
        private publicPath: string = process.env.BASE_URL;
        private filePath: string = require("@/assets/images/user-no-face.jpg");
        @State("UserStore")
        public user!: InterfaceUser;
        private friends: any[] = [];
        private page: number = 1;
        private loveArticleImg: string = "";
        private rankType: string = "all";
        private sortValue: number = 1;
        private allRank: number = 0;
        private ageRank: number = 0;
        private incomeRank: number = 0;
        private clientWidth = document.body.clientWidth;

        private selectDrawerShow: boolean = false;
        private currentKey: string = "";
        private currentSnap: string = "";
        private currentChilrenKey: string = "";
        private diffPicket: any = "";
        private diffDataList: any[] = [];
        private currentKeyArray: string[] = [];
        private currentSnapArray: string[] = [];
        private addressJson: any[] = [];
        private addressPicker: any = "";
        private commonPicker: any = "";
        private selectValue: any = {
            mate_age: "",
            mate_age_snap: "",
            mate_height: "",
            mate_height_snap: "",
            mate_education: "",
            mate_education_snap: "",
            mate_income: "",
            mate_income_snap: "",
            mate_province: "",
            mate_province_snap: "",
            mate_city: "",
            mate_city_snap: "",
            mate_marital: "",
            mate_marital_snap: "",
            mate_housing: "",
            mate_housing_snap: "",
            mate_child: "",
            mate_child_snap: ""
        };
        private tagList:any[] = [];

        private get submitSelectValue(): any {
            const submitSelectValue: any = {};
            if (this.selectValue.mate_age) {
                submitSelectValue.mate_age = this.selectValue.mate_age;
            }
            if (this.selectValue.mate_height) {
                submitSelectValue.mate_height = this.selectValue.mate_height;
            }
            if (this.selectValue.mate_education) {
                submitSelectValue.mate_education = this.selectValue.mate_education;
            }
            if (this.selectValue.mate_income) {
                submitSelectValue.mate_income = this.selectValue.mate_income;
            }
            if (this.selectValue.mate_province) {
                submitSelectValue.mate_province = this.selectValue.mate_province;
            }
            if (this.selectValue.mate_city) {
                submitSelectValue.mate_city = this.selectValue.mate_city;
            }
            if (this.selectValue.mate_marital) {
                submitSelectValue.mate_marital = this.selectValue.mate_marital;
            }
            if (this.selectValue.mate_housing) {
                submitSelectValue.mate_housing = this.selectValue.mate_housing;
            }
            if (this.selectValue.mate_child) {
                submitSelectValue.mate_child = this.selectValue.mate_child;
            }
            return submitSelectValue;
        }


        private get options(): any {
            return {
                pullDownRefresh: {txt: "更新成功"},
                pullUpLoad: {
                    threshold: 0,
                    txt: {more: "", noMore: "没有更多数据..."},
                    visible: true
                },
                scrollbar: true
            };
        }

        private onPullingDown(): void {
            this.page = 1;
            this.$nextTick(() => {
                Http.get(this.api.centerRecommendObject, {page: this.page, size: 20, ...this.submitSelectValue}, {token: this.user.token}).then((res) => {
                    if (res.code == 1) {
                        if (res.data.data !== []) {
                            this.friends = [];
                            this.friends = this.friends.concat(res.data.data);
                            this.page++;
                            this.$nextTick(() => {
                                (this as any).$refs.scroll.forceUpdate();
                                (this as any).$refs.scroll.refresh();
                            });
                        } else if (res.data.data == []) {
                            (this as any).$refs.scroll.forceUpdate();
                        }
                    }
                });
            });
            // (this as any).$refs.scroll.forceUpdate();
        }

        private onPullingUp(): void {
            Http.get(this.api.centerRecommendObject, {page: this.page, size: 20, ...this.submitSelectValue}, {token: this.user.token}).then((res) => {
                console.log(res);
                if (res.code == 1) {
                    if (res.data.data !== []) {
                        this.friends = this.friends.concat(res.data.data);
                        this.page++;
                        this.$nextTick(() => {
                            (this as any).$refs.scroll.refresh();
                            (this as any).$refs.scroll.forceUpdate();
                        });
                    } else if (res.data.data == []) {
                        (this as any).$refs.scroll.forceUpdate();
                    }
                }
            });
        }

        private toPage(name: string, query: any = {}): any {
            if (name === "chatDetail") {
                if (this.user.userRank < 2) {
                    const dialogConfig = new DialogConfig();
                    (<any> this).$createDialog({
                        ...dialogConfig.getBecomeMemberConfig(),
                        onConfirm: () => {
                            this.navigateTo({
                                name: "mineMemberRank",
                                query: {
                                    back: 1
                                }
                            });
                        }
                    }).show();
                } else {
                    this.navigateTo({
                        name: name,
                        query: query
                    });
                }
            } else {
                this.navigateTo({
                    name: name,
                    query: query
                });
            }
        }

        private getLoveArticleImg(): void {
            Http.get(this.api.matchCenterPicture).then((res) => {
                if (res.code == 1) {
                    this.loveArticleImg = res.data.file_path;
                } else {
                    const loadToast = (<any> this).$createToast({
                        time: 2500,
                        type: "error",
                        mask: true,
                        txt: `${res.msg}`,
                        onTimeout: () => {
                            this.navigateBack();
                        }
                    }).show();
                }
            }).catch((res) => {
                console.log(res);
            });
        }

        private getFriendList(isNew = false): void {
            let loadToast = (<any> this).$createToast({
                time: 0,
                type: "loading",
                mask: true,
                txt: "加载中..."
            }).show();
            if (isNew) {
                this.page = 1;
            }
            Http.get(this.api.centerRecommendObject, {page: this.page, size: 20, ...this.submitSelectValue}, {token: this.user.token}).then((res) => {
                if (res.code == 1) {
                    loadToast.hide();
                    this.page++;
                    this.friends = res.data.data;
                } else {
                    loadToast.hide();
                    this.globalSingleResultToast(res);
                }
            }).catch((res) => {
                (<any> this).$createToast({
                    time: 2500,
                    type: "error",
                    txt: "网络繁忙,暂无信息!",
                    mask: true,
                    onTimeout: () => {
                        this.navigateBack();
                    }
                }).show();
            });
        }

        private like(isLike: number, id: number, index: number): void {
            try {
                if (isLike) {
                    Http.post(this.api.cancelPreferById, {id: id}, {token: this.user.token}).then((res) => {
                        if (res.code == 1) {
                            this.friends[index].like = 0;
                        } else {
                            this.globalSingleResultToast(res);
                        }
                    });
                } else {
                    Http.post(this.api.preferById, {id: id}, {token: this.user.token}).then((res) => {
                        if (res.code == 1) {
                            this.friends[index].like = 1;
                        } else {
                            this.globalSingleResultToast(res);
                        }
                    });
                }
            } catch (e) {
                console.log(e);
            }
        }

        private activated() {
            if (this.friends.length === 0 && this.loveArticleImg !== "") {
                this.getFriendList(true);
            }
        }

        private mounted() {
            this.getLoveArticleImg();
            this.getFriendList(true);

            this.commonPicker = (<any> this).$createPicker({
                title: "",
                data: [],
                onSelect: this.selectCommonValue,
            });
        }

        private toExpertList() {
            this.navigateTo({
                name: "expertList"
            });
        }

        private async showDiffPicker(title: string, key: string, snap: string, type: string, subtitle: string = "", childrenKey: string = ""): Promise<any> {
            this.currentKey = key;
            this.currentSnap = snap;
            this.currentChilrenKey = childrenKey;
            const toast = (<any> this).$createToast({
                time: 0,
                txt: "载入数据中...",
                mask: true
            }).show();
            if (!this.diffPicket) {
                this.diffPicket = (<any> this).$createPicker({
                    title: "",
                    onChange: this.diffValueChange,
                    onSelect: this.diffValueSelect
                });
            }
            const result: any = await Http.get(this.api.getParameterItem, {type});
            this.diffDataList = CommonUnit.resultToPickerData(result.data);
            this.diffPicket.$updateProps({
                title: title,
                data: [this.diffDataList, this.diffDataList],
            });
            toast.hide();
            this.diffPicket.show();
        }

        private diffValueChange(col: number, selectedIndex: number): void {
            if (col === 0) {
                this.diffPicket.setData([this.diffDataList, this.diffDataList.slice(selectedIndex)], [selectedIndex, 0]);
            }
        }

        private diffValueSelect(value: any[], index: number[], text: string[]) {
            if (this.currentChilrenKey === "mateSelection") {
                this.$set(this.selectValue, this.currentKey, value.join(","));
                this.$set(this.selectValue, this.currentSnap, text[0] === text[1] ? text[0] : text.join("～"));
            }

        }

        private async showAddressPicker(title: string, key: string[], snap: string[], childrenKey: string = ""): Promise<any> {
            this.currentKeyArray = key;
            this.currentSnapArray = snap;
            this.currentChilrenKey = childrenKey;

            const toast = (<any> this).$createToast({
                time: 0,
                txt: "载入地区数据",
                mask: true
            }).show();
            let result: any[] = await Http.read(this.api.addressJson);
            if (key.length !== 3) {
                for (let i in result) {
                    for (let j in result[i].children) {
                        delete result[i].children[j].children;
                    }
                }
            }
            if (childrenKey === "mateSelection") {
                const addressJson = result;
                for (let i in addressJson) {
                    addressJson[i].children.unshift({pid: addressJson[i].value, text: "不限", value: -1});
                }

            }
            this.addressJson.push(...result);
            toast.hide();
            this.addressPicker = (<any> this).$createCascadePicker({
                title: title,
                data: result,
                onSelect: this.addressSelect,
            });

            this.addressPicker.show();
        }

        private selectCommonValue(value: any[], index: number[], text: string[]) {
            if (this.currentChilrenKey === "mateSelection") {
                this.$set(this.selectValue, this.currentKey, value.join(","));
                this.$set(this.selectValue, this.currentSnap, text.join(","));
            }
        }

        private addressSelect(value: any[], index: number[], text: string[]) {
            if (this.currentChilrenKey === "mateSelection") {
                this.$set(this.selectValue, "mate_province", value[0]);
                this.$set(this.selectValue, "mate_city", value[1]);
                this.$set(this.selectValue, "mate_province_snap", text[0]);
                this.$set(this.selectValue, "mate_city_snap", text[1]);
            }

        }

        private selectSubmit() {
            this.getFriendList(true);
            this.getTagText();
            this.selectDrwaerHandle();
        }

        private selectReset() {
            this.selectValue = {
                mate_age: "",
                mate_age_snap: "",
                mate_height: "",
                mate_height_snap: "",
                mate_education: "",
                mate_income: "",
                mate_income_snap: "",
                mate_province: "",
                mate_province_snap: "",
                mate_city: "",
                mate_city_snap: "",
                mate_marital: "",
                mate_marital_snap: "",
                mate_housing: "",
                mate_housing_snap: "",
                mate_child: "",
                mate_child_snap: ""
            };
        }

        private selectDrwaerHandle() {
            this.selectDrawerShow = !this.selectDrawerShow;
        }

        private async showCommonPicker(title: string, key: string, snap: string, type: string, subtitle: string = "", childrenKey: string = ""): Promise<any> {
            const toast = (<any> this).$createToast({
                time: 0,
                txt: "载入选项中...",
                mask: true
            }).show();
            this.currentKey = key;
            this.currentSnap = snap;
            this.currentChilrenKey = childrenKey;
            const result = await Http.get(this.api.getParameterItem, {type});
            this.commonPicker.$updateProps({
                title: title,
                subtitle: subtitle,
                data: [CommonUnit.resultToPickerData(result.data)],
            });
            toast.hide();
            this.commonPicker.show();
        }

        private getTagText() {
            const tagList = [];
            if (this.selectValue.mate_age_snap) {
                tagList.push('年龄:'+this.selectValue.mate_age_snap);
            }
            if (this.selectValue.mate_height_snap) {
                tagList.push('身高:'+this.selectValue.mate_height_snap);
            }
            if (this.selectValue.mate_education_snap) {
                tagList.push('文化程度:'+this.selectValue.mate_education_snap);
            }
            if (this.selectValue.mate_income_snap) {
                tagList.push('收入:'+this.selectValue.mate_income_snap);
            }
            if (this.selectValue.mate_province_snap) {
                tagList.push('居住地:'+this.selectValue.mate_province_snap + "," + this.selectValue.mate_city_snap);
            }
            if (this.selectValue.mate_marital_snap) {
                tagList.push('婚姻:'+this.selectValue.mate_marital_snap);
            }
            if (this.selectValue.mate_housing_snap) {
                tagList.push('房产:'+this.selectValue.mate_housing_snap);
            }
            if (this.selectValue.mate_child_snap) {
                tagList.push('小孩:'+this.selectValue.mate_child_snap);
            }
            this.tagList = tagList;

        }
    }
</script>

<style scoped lang="stylus">
    .view
        height calc(100vh - 47px - var(--safe-area-inset-bottom));
        background $theme-page-common-background-color;

        .friend-head
            border-top 1px solid $theme-line-color;
            border-bottom 1px solid $theme-line-color;

            img
                width 100vw;
                height 30vw;
                display block;

            .handle
                line-height 40px;
                text-align center;
                color $theme-common-color;
                background-color #fff;


        .friend-filter-nav
            height 40px;
            background #fff;
            display flex;
            align-items center
            flex-wrap wrap
            padding 0 10px
            border-bottom 1px solid $theme-line-color;
            span
                padding 3px 4px;
                border-radius 2px;
                font-size 10px
                &.tag
                    margin-right 5px;
                    background #ec6786;
                    color #fff

        .none-friends
            height calc(100vh - 47px - var(--safe-area-inset-bottom) - 30vw - 44px - var(--safe-area-inset-top));
            padding-top 100px;
            text-align center;

        .scroll
            height calc(100vh - 47px - var(--safe-area-inset-bottom) - 30vw - 44px - 40px - var(--safe-area-inset-top));
            background-color #fff;

            .list-wrapper
                .list-item
                    margin 0px 7px;
                    padding 7px 0;
                    justify-content: space-around;
                    align-items start;
                    border-bottom 1px solid $theme-line-color;

                    .avatar
                        width 70px;
                        height 70px;
                        border-radius 50%;
                        position relative;

                        img
                            width 70px;
                            height 70px;
                            border-radius 50%;

                    .info
                        width calc(100vw - 85px - 14px - 30px);
                        line-height 24px;

                        .nickname
                            font-size 15px;
                            color #333

                            svg
                                font-size 14px;

                        .factor
                            span
                                padding 0 5px;
                                border-right 1px solid $theme-line-color;

                                &:last-child
                                    border-right none;

                                &:first-child
                                    padding-left 0;

                        .hobby
                            span
                                padding 0 5px;

                                &:last-child
                                    border-right none;

                                &:first-child
                                    padding-left 0;

                        .rank
                            color $theme-viceColor-font;

                            svg
                                font-size 18px;

                        .intro
                            color $theme-viceColor-font;

                        .handdle
                            text-align right;
                            color $theme-common-color;

                            span.like
                                margin-right 20px;

                            .distance
                                color $theme-viceColor-font;


</style>
